package com.gmall.product.aspect;


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

@Aspect
@Component
public class MyTransactionalAspect {

    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    @Pointcut(value = "@annotation(com.gmall.product.annotation.MyTransactional)")
    public void myTransactionalPointCut(){

    }

    @Around("myTransactionalPointCut()")
    public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
        System.out.println("----------- 开始事务 -----------");

        //开启事务
        DefaultTransactionDefinition defaultTransactionDefinition =
                new DefaultTransactionDefinition();
        // 嵌套事务
        defaultTransactionDefinition.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);//
        defaultTransactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        // 设置嵌套事务
        TransactionStatus status = platformTransactionManager.getTransaction(defaultTransactionDefinition);

        try {
            Object proceed = proceedingJoinPoint.proceed();//执行方法本身
            platformTransactionManager.commit(status);//提交事务
            System.out.println("-----提交事务");
            return proceed;
        }catch (RuntimeException e){
            //platformTransactionManager.rollback(status);
            System.out.println("-----回滚事务");
            return null;
        }catch (Exception e2){
            platformTransactionManager.rollback(status);
            System.out.println("-----回滚事务");
            return null;
        }
    }
}
